package com.yeskery.nut.plugin;

import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.bean.FactoryBeanRegister;
import com.yeskery.nut.core.NutException;

import java.util.Collection;
import java.util.Collections;
import java.util.logging.Logger;

/**
 * 应用上下文支持基础插件
 * @author sprout
 * @version 1.0
 * 2022-07-07 21:59
 */
public class ApplicationContextSupportBasePlugin implements Plugin {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(ApplicationContextSupportBasePlugin.class.getName());

    /** 应用上下文 */
    private ApplicationContext applicationContext;

    @Override
    public void bind(BindContext bindContext) {
        applicationContext = bindContext.getNutApplication().getApplicationContext();
        FactoryBeanRegister factoryBeanRegister = null;
        if (applicationContext instanceof FactoryBeanRegister) {
            factoryBeanRegister = (FactoryBeanRegister) applicationContext;
        }

        Collection<PluginBeanMetadata> registerPluginBeanMetadata = getRegisterPluginBeanMetadata();
        if (registerPluginBeanMetadata != null && !registerPluginBeanMetadata.isEmpty()) {
            for (PluginBeanMetadata pluginBeanMetadata : registerPluginBeanMetadata) {
                Class<?>[] types = pluginBeanMetadata.getTypes();
                if (types == null || types.length == 0) {
                    throw new NutException("PluginBeanMetadata Types Must Not Be Empty.");
                }
                Object bean = pluginBeanMetadata.getBean();
                if (factoryBeanRegister != null) {
                    if (factoryBeanRegister.containBean(pluginBeanMetadata.getBeanName())) {
                        logger.warning("Plugin [" + this.getClass().getName() + "] Bind Resource Bean Name ["
                                + pluginBeanMetadata.getBeanName() + "] Already Registered.");
                        continue;
                    }
                    factoryBeanRegister.registerBean(pluginBeanMetadata.getBeanName(), bean, types);
                }
            }
        }
    }

    /**
     * 获取要注册的插件Bean元数据集合
     * @return 要注册的插件Bean元数据集合
     */
    protected Collection<PluginBeanMetadata> getRegisterPluginBeanMetadata() {
        return Collections.emptySet();
    }

    /**
     * 获取应用上下文
     * @return 应用上下文
     */
    protected ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
